package org.niugang.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.niugang.bean.UserQueryBean;
import org.niugang.entity.UserEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;


/**
 * 授权认证业务类
 *
 * @author niugang UserDetailsService spring security包里面的
 * 重写loadUserByUsername方法
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    // UserService自定义的，从数据查询信息
    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户是否存在
        UserEntity queryList = userService.getUserByAccount(username);
        if (queryList != null) {
            //   查询用户拥有的角色
            List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
            // 如果是admin用户登录，授予SUPERADMIN权限
            if (username.equals("admin")) {
                list.add(new SimpleGrantedAuthority("SUPERADMIN"));
            }

            org.springframework.security.core.userdetails.User authUser = new org.springframework.security.core.userdetails.User(
                    queryList.getAccount(), queryList.getPassword(), list);

            return authUser;
        }
        return null;

    }

}
